Uec3.AddReceiveItemWindow = Ext.extend(Ext.app.Module,{
	id : 'addReceiveItem',
	
	init : function(initParams){
   		
    },
    getComponent : function(params){
    	
    	 var _this = this;  
    	
    	 var receiveItem_grid = params.grid;
    	 
	     var record = params.record;
    	 
	     var isAdd = params.isAdd;
	     
	     var hasOrder = params.hasOrder;
	     
    	 var ds_code_select = new Ext.data.JsonStore({
	    	 	url:Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeImplicitExt.do",
	     		root:'root',
	     		totalProperty:'totalProperty',
        		fields:[{name:'code',type:'string'},{name:'name',type:'string'}]
	 	});
    	
	 	var ds_source_select = new Ext.data.JsonStore({
	      		url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=part_source",
	     		root: "",
	      		//autoLoad :true,
	      		fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
	  	});  
	 	
	  	var ds_publicanLevel_select = new Ext.data.JsonStore({
	      		url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=partproperty_publicanLevel",
	      		root: "",
	      		//autoLoad :true,
	      		fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
	  	});
	  	
	  	var store_ds = new Ext.data.JsonStore({
				url : Uec3.App.Constants.homeUrl+ '/store/base!query.do',
				root:'root',
				totalProperty: "totalProperty",
				fields:[
					{name : 'id',type:'int'},
					{name : 'name',type:'string'},
					{name : 'pyCode',type:'string'},
					{name : 'departmentName',type:'string'}
				]
		});
	  	
		// Custom rendering Template
        var resultTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
               '{name},{departmentName}',             
            '</div></tpl>'
        );
		
    	var detailForm = new Ext.FormPanel({
    		 frame:true,
    		 border:false,
    		 labelAlign:'left',
    		 labelWidth:52,	     
    	     items:[
    	     	{
					xtype:'fieldset',
					title:'零件属性信息',
					height:160,
					layout:'uec3grid',
					layoutConfig:{
					  hGrid:[10,40,10,40],
					  vGrid:[20,20,20,20,20]
				
					},
					defaults:{enableKeyEvents : true},
    	       		items:[
    	       			{xtype:'label',text:'零件编码'},
    	       			{	
		       				xtype:'combo',				    													 
							blankText : '零件编码不能为空',
							hiddenName : 'code',					
							fieldLabel:'零件编码',
					        valueField:'code',
		            		displayField : 'code',
							mode : 'remote',
							queryParam :'queryParam',
							queryDelay:500,
							minChars :2,
							store : ds_code_select,  	  								 
							pageSize:10,
						    selectOnFocus : true,
						    triggerAction : 'all',
						    loadingText : '加载中...',	   				
		                    emptyText : '请输入至少2位零件编码',
		                    listWidth:270,
		                    readOnly:false,
		                    style:{},
		                    //focusOrder:1,
		                    listeners :{
		                       'select':function(){
		   	                       var value = this.getValue();
		      					   detailForm.getForm().el.dom.reset();
		                           this.setValue(value);
		                       },
		                       'change':function(){
		   	                        var value = this.getValue();
		                            detailForm.getForm().el.dom.reset();
		                            this.setValue(value);
		                       }
							} 
						},
						{xtype:'label',text:'零件来源'},
    	       			{
							xtype:'combo',				   
							fieldLabel:'零件来源',
							valueField:'varIndex',
							displayField : 'varName',
							mode : 'remote',
							hiddenName:'source',
							value:'',
							store : ds_source_select,
							selectOnFocus : true,
							forceSelection  :true,
							editable:true,
							triggerAction : 'all',
							loadingText : '加载中...',	   				
							emptyText : '请选择零件来源',
							//focusOrder:2,
							readOnly:false,
							style:{},
							listeners :{
								'select':autoFillDetailForm
							}
						},
						{xtype:'label',text:'零件名称'},
    	       			{
							xtype:'textfield',				    									  
							name : 'name',
							fieldLabel:'零件名称',
							readOnly:true,
							style:{background:'#dddddd'}
   			  			},
   			  			{xtype:'label',text:'单位'},
						{
							xtype:'textfield',				    									
							name : 'measurementUnit',
							fieldLabel:'单位',
							readOnly:true,
							style:{background:'#dddddd'}					               
						},
						{xtype:'label',text:'品牌'},
    	       			{
       			  			xtype:'textfield',							
							name : 'brand',
			                fieldLabel:'品牌',
							readOnly:true,
							style:{background:'#dddddd'}
			                //focusOrder:4
     			  		},
   			  			{xtype:'label',text:'车型'},
	  					{
	   			  			xtype:'textfield',
	   			  			name:'carModel',
	   			  			fieldLabel:'车型',
							readOnly:true,
							style:{background:'#dddddd'}
	   			  			//focusOrder:3
						},
     			  		{xtype:'label',text:'公开级别'},
						{
							xtype:'combo',				   
							name : 'publicanLevel',
							fieldLabel:'公开级别',
							valueField:'varIndex',
							displayField : 'varName',
							hiddenName:'publicanLevel',
							mode : 'remote',
							store : ds_publicanLevel_select,
							selectOnFocus : true,
							forceSelection  :true,
							editable:false,
							triggerAction : 'all',
							loadingText : '加载中...',
							editable:false,
							readOnly:true,
							style:{background:'#dddddd'}
							//emptyText : '请选择零件公开级别',
							//focusOrder:5
						},
     			  		{xtype:'label',text:'媒体价'},						
						{
							xtype:'numberfield',									
							name : 'retailPrice',
							fieldLabel:'媒体价',
							readOnly:true,
							style:{background:'#dddddd'}								
							//focusOrder:6
						},						
     			  		{xtype:'label',text:'最低价'},						
						{
							xtype:'numberfield',
							name : 'minPrice',
							fieldLabel:'最低价',
							allowNegative: false,
							readOnly:true,
							style:{background:'#dddddd'}
							//focusOrder:7
						},
     			  		{xtype:'label',text:'保险价'},						
						{
							xtype:'numberfield',									
							name : 'insurancePrice',
							fieldLabel:'保险价',
							readOnly:true,
							style:{background:'#dddddd'}								
							//focusOrder:8
						}
    	       		]
    	     	},
				{
					xtype:'fieldset',
					title:'入库信息',
					height:110,
					layout:'uec3grid',
					layoutConfig:{
						hGrid:[10,40,10,40],
						vGrid:[33,33,33]
					},
					defaults:{enableKeyEvents : true},
					items:[
						{xtype:'label',text:'订购数量'},
						{
		 		         	xtype:'numberfield',				
						 	name : 'orderQuantity',
						 	fieldLabel:'订购数量',					
		                 	allowNegative: false,
		                 	readOnly:true,
				         	style:{background:'#dddddd'}
		 		       	},
		 		       	{xtype:'label',text:'产地'},
		 		       	{
							xtype:'textfield',
							allowBlank : false,
							blankText : '产地不能为空',
							name : 'origin',
							fieldLabel:'产地'
							//focusOrder:9
    	     		    },	
    	     		    {xtype:'label',text:'入库数量'},
						{
							xtype:'numberfield',
							allowBlank : false,
							name : 'quantity',
							fieldLabel:'入库数量',
							allowBlank: false,
							allowNegative: false
							//focusOrder:10
						},
						{xtype:'label',text:'进价'},
						{
							xtype:'numberfield',
							allowBlank : false,
							name : 'cost',
							fieldLabel:'进价',
							allowBlank: false,
							allowNegative: false
							//focusOrder:12
						},
						{xtype:'label',text:'仓库'},
						{
							xtype:'lookupBox2',
							fieldLabel : '仓库',
							itemId:'store_lookup',
							store: store_ds,
							displayField:'name',
							lookupField:'pyCode',
							name:'storeName',
							valueField:'id',
							allowBlank:false,
							typeAhead: true,
							tpl: resultTpl,
							itemSelector: 'div.search-item',
							mode: 'remote',
							triggerAction: 'all',
							emptyText:'请选择仓库...',
							selectOnFocus:true, 			
							queryDelay:10,
							typeAheadDelay:10,
							pageSize:5,
							autoDestory:true,
							queryParam:'keyword',
							app:this.app,
							listWidth:250,
							triggerTags:[{moduleId: 'store_list',triggerClass:'x-form-search-trigger'},{moduleId: 'store_add'}]
							//focusOrder:11
						},						
						{xtype:'label',text:'仓位'},  
						{
							xtype:'textfield',
							name : 'shelf',
							fieldLabel:'仓位'
							//focusOrder:13
						}
					] 
				}    
    	     ],
			 buttons:[
			     {			     
			        handler:submitForm,
			        iconCls:'icon-save'
			     },{			     	
			        handler:resetForm
			     },{			     	
			     	handler:function(){				     		
			     	   detailForm.ownerCt.close();
			     	}
			     }
			 ],
			 buttonAlign:'center'
    	});
    	
    	 /**
         * 根据零件code、source查找零件信息
         */	  
	    function autoFillDetailForm(){
	    	 var source = this.getValue();
	    	 var code = detailForm.getForm().findField("code").getValue();
	    	 if(code){
	    	 	 var myMask = new Ext.LoadMask(detailForm.ownerCt.el,{msg : '查询零件属性中....'});
	    	 	 myMask.show();
	    	     Ext.Ajax.request({
	    	        url :Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeAndSource.do",
	                params :{queryParam:Ext.encode({code:code,source:source})},
	                method :"post",
	                callback :function(options,success,response){
	                     myMask.hide();
	                },
	                success:function(response,options){	                	 
	                	  var resp = Ext.decode(response.responseText);
	                	  if(resp.success){
	                	  	 detailForm.getForm().setValues(resp);
	                	  	 if(resp.hasPro){	                	     	
	                	     	var carModelField = detailForm.getForm().findField("carModel");
	                	     	var carModel = carModelField.getValue();	                	     
	                	     	if(carModel){
	                	     		var sourceField = detailForm.getForm().findField("source");
	                	     		sourceField.blur();
	 		                        sourceField.hasFocus=false;
	                	     		detailForm.getForm().findField("origin").focus();
	                	     	}else{
	                	     	   carModelField.focus();
	                	     	}	                	     	
	                	  	 }else{
	                	     	Ext.MessageBox.alert("提示",resp.msg,function(){	                	     		
	                	     		delete resp.msg;
	                	     		delete resp.success;
	                	     		delete resp.hasPro;
	                	     		var desktop=Uec3.App.getDesktop();	                	     		
									desktop.launchWindowByParam("partPropertyOperation",{type:'add',data:resp,fn:function(record){
										delete record.cost;
										detailForm.getForm().setValues(record);
									}});
	                	     	});	                	     	
	                	     }	
	                	  }else{
	                	   	  Ext.MessageBox.alert("提示",resp.msg);
	                	  }
	                	  				       
	                },
	                failure:function(response,options){
	                      Ext.MessageBox.alert("提示","数据加载异常");
	                }
	    	   });	    		    	 
	       }else{
	         Ext.MessageBox.alert("提示","请填写零件编码");
	       }	    		         
	    }
	    
	    function resetForm(){
	  	    if(isAdd){
	  	       var fieldNames = ['code','source','name','retailPrice','minPrice','insurancePrice','quantity','cost','shelf'] 
	  	       //detailForm.form.el.dom.reset();
	  	       Ext.each(fieldNames,function(fieldName,index,fieldNames){
	  	           var field= detailForm.form.findField(fieldName);
	  	           field.el.dom.value='';
	  	       });
	  	    }else{
	  	       var columns=receiveItem_grid.getColumnModel().columns;
	           Ext.each(columns,function(value,index,arr){
	               var cellName=value.dataIndex;
	               var field= detailForm.form.findField(cellName);
				   if(field&&!field.readOnly){
				      field.el.dom.value='';
				   }		             
	           });
	  	    }	  	    
	   }
	    
	   function submitForm(){
	  	   //取得表单数据	
	   	   var form = detailForm.getForm();
	       if(!form.isValid()){
	       	  form.items.each(function(f){
				if(!f.isValid()){
					f.focus(true,300);
					return false;
				}
			});
	          return;
	       }	
	       detailForm.enable();
	       var  newRecord= form.getValues();
	       var store_lookup=form.findField("storeName");	      
	       var storeId = store_lookup.value;
	       var storePyCode = store_lookup.lookupValue;	       
	       newRecord.storeId= storeId;
	       newRecord.storePyCode = storePyCode;
	       var receiveItem_store = receiveItem_grid.getStore();
	       var index= receiveItem_store.findExact('code',newRecord.code);
	       if(index != -1){
	       	   //修改明细
			   var item = receiveItem_store.getAt(index);
			   for(var fieldName in newRecord){
				   item.set(fieldName,newRecord[fieldName]);
			   }
			   receiveItem_store.commitChanges();			    
	       }else{
	          //增加明细
	       	  receiveItem_store.add(new Ext.data.Record(newRecord));	       	  
              receiveItem_grid.getSelectionModel().selectFirstRow();
	       }
	       if(isAdd){
	  	       resetForm();
	  	       enableSpecificField(['code','source']);
	  	       form.findField("code").focus();
	  	   }else{
	  	        detailForm.ownerCt.close();
	  	   }
	   }
	    
	   function init(){
	   	    var count=0;
	    	ds_source_select.load();
	    	ds_publicanLevel_select.load({callback:function(){
	    		if(++count==1){
	    			initForm();
	    		}
	    	}});
	    	
	   }
	   function initForm(){
	   	 if(isAdd){
	    		detailForm.buttons[0].setText('新增');
	    		detailForm.buttons[1].setText('重置');
	    		detailForm.buttons[2].setText('关闭');
	    		//detailForm.getForm().findField("code").focus();
	    	}else{
	    		detailForm.buttons[0].setText('修改');
	    		detailForm.buttons[1].setText('重置');
	    		detailForm.buttons[2].setText('关闭');	    		
	    		var columns=receiveItem_grid.getColumnModel().columns;         
	            Ext.each(columns,function(value,index,arr){
	                 var cellName=value.dataIndex;
	                 var cellEditor=value.editor; 	       
	                 if(!cellEditor){
	             	    var field=detailForm.form.findField(cellName); 
	             	    if(field){
	             	       field.setReadOnly(true);
	             	       field.setWidth(200);	             	      
	             	       field.getEl().setStyle('background','#dddddd');					    
	             	    }					
	                 }
	            });  	    		
	            detailForm.getForm().loadRecord(record);  
		        var store_lookup = detailForm.getForm().findField("storeName");		       
		        store_lookup.initializeValue({'id':record.data.storeId,'name':record.data.storeName,'pyCode':record.data.storePyCode});
	    	}
	   }
	   
	   function disableSpecificField(fieldArr){
	   		Ext.each(fieldArr,function(fieldName,index,fieldArr){
	   			var field = detailForm.getForm().findField(fieldName);
	   			 field.setReadOnly(true);	
	             field.setWidth(207);	             	      
	             field.getEl().setStyle('background','#dddddd');
	   		});
	   }
	   
	   function enableSpecificField(fieldArr){
	   		Ext.each(fieldArr,function(fieldName,index,fieldArr){
	   			var field = detailForm.getForm().findField(fieldName);
	   			field.setReadOnly(false);
	             field.getEl().setStyle('background','');
	   		});
	   }
	   
	   init();  
	   return detailForm;
    },
    /**
	* Create this modules window here.
	*/
    createWindow : function(params){
    	var desktop = this.app.getDesktop();
    	var title;
    	if(params.isAdd){
    	    title = '新增入库明细';
    	}else{
    		title = '编辑入库明细';
         }
        var win = desktop.getWindow('addReceiveItemWindow');
        if (!win) {
			win = desktop.createWindow({
				        id : "addReceiveItemWindow",
						title : title,
						width : 570,
						autoHeight : true,
						iconCls : 'acc-icon',
					    //minWidth:1000,
						maximizable : true,
						resizable:false,
						maximized:false,
						//autoScroll : true,
						constrainHeader : true,
						taskbuttonTooltip : title,
						minimizable : false,
						items : [this.getComponent(params)]
			});
		} 
		Ext.util.Observable.capture(win,function(e){
	     	if(e=='show'){
	   		    formBingingKeys(this.get(0),win);
	   	    }
	    });
    	win.show();
    	
    }
});